import { useEffect, useState } from "react";
import { Button, Input, View } from "@tarojs/components";
import {
  C13BottomDock,
  C37GiftCertificateCard,
  CheckBox,
  Layout,
  Paragraph,
  WithMargins,
} from "@/components";
import { useAuth } from "@/store/authContext";
import { GiftCertificateShape } from "@/data/user/userTypes";
import { useApplicationInfo } from "@/store/applicationDataContext";
import Taro, { useDidShow, useRouter } from "@tarojs/taro";
import {
  addUserGiftCard,
  getUserGifts,
  useUserInfo,
} from "@/store/userDataContext";
import { alert } from "@/utils";
import { navigateTo } from "@/utils/navigation";
import style from "./index.module.scss";

// Selected gift card should be a single one
// from manual input or in list
// Or none at all
export default function GiftCertificateSelect() {
  const { params } = useRouter();
  const { dispatchAuthAction } = useAuth();
  const { applicationState, dispatch } = useApplicationInfo();
  const { userInfoState, dispatchUserDataAction } = useUserInfo();
  const { selectedGiftCard } = applicationState;
  const [giftCardKeyInput, setGiftCardKeyInput] = useState("");
  const [selectedGiftNumber, setSelectedGiftNumber] =
    useState<GiftCertificateShape | null>(selectedGiftCard);
  const [gifts, setGifts] = useState<Array<GiftCertificateShape>>([]);

  const getGiftCards = async () => {
    if (params.preOrderNo) {
      const giftcards = await getUserGifts(
        dispatchUserDataAction,
        userInfoState.userData!,
        {
          query: {
            limit: process.env.defaultPageSize!,
            page: 1,
            preOrderNo: params.preOrderNo,
          },
          authDispatch: dispatchAuthAction,
        }
      );
      const newGifts =
        giftcards &&
        giftcards.map((gc: any) => {
          return {
            ...gc,
            title: gc.name,
          };
        });
      setGifts(newGifts);
    }
  };

  useDidShow(() => {
    getGiftCards();
  });

  useEffect(() => {
    if (selectedGiftNumber !== selectedGiftCard) {
      dispatch({ type: "SELECTED_GIFT_CARD", data: selectedGiftNumber });
    }
  }, [selectedGiftNumber]);

  const addGiftCard = () => {
    addUserGiftCard({ query: { cardKey: giftCardKeyInput } }, () => {
      setGiftCardKeyInput("");
      getGiftCards();
      alert("兑换成功");
    });
  };

  return (
    <>
      <Layout>
        <WithMargins>
          <View className={style["gift-certificate-select-wrapper"]}>
            {gifts && (
              <>
                <Paragraph className={style["top-text"]} size="small" noSpacing>
                  选择您的礼品卡
                </Paragraph>

                {/* Manual input */}

                <View className={style["small-title"]}>实体礼品卡</View>
                <View className={style["manual-code"]}>
                  <Input
                    className={style["manual-code-input"]}
                    type="text"
                    value={giftCardKeyInput}
                    placeholder="请输入序列号"
                    onInput={(e) => {
                      setGiftCardKeyInput(e.detail.value);
                    }}
                    // onBlur={() => {
                    //   // TODO: possible to add validation of valid gift card ID on blur
                    //   setSelectedGiftNumber(+manualGiftInput);
                    // }}
                  />
                  <Button
                    className={style["manual-code-submit"]}
                    plain
                    onClick={addGiftCard}
                  >
                    <Paragraph color="#00a4b6" size="small">
                      兑换礼品卡
                    </Paragraph>
                  </Button>
                </View>

                {/* Selection of existing gift cards */}
                <View className={style["my-gift-cards"]}>
                  <View className={style["small-title"]}>选择电子礼品卡</View>
                  <View
                    className={style["my-gift-cards-link"]}
                    onClick={() =>
                      navigateTo("pages/user-gift-certificates/index")
                    }
                  >
                    <Paragraph
                      color="#00a4b6"
                      size="small"
                      className="underline"
                    >
                      查看我的礼品卡
                    </Paragraph>
                  </View>
                </View>

                {gifts.length ? (
                  gifts.map((giftCertData) => (
                    <View
                      key={giftCertData.id}
                      className={style["gift-card-container"]}
                    >
                      <CheckBox
                        onChangeCb={(e) => {
                          const checked = !!e.detail.value.length;
                          if (checked) {
                            setSelectedGiftNumber(giftCertData);
                          } else {
                            setSelectedGiftNumber(null);
                          }
                        }}
                        checked={
                          !!selectedGiftNumber &&
                          selectedGiftNumber.id === giftCertData.id
                        }
                      />
                      <C37GiftCertificateCard
                        type="small"
                        colorTheme={{
                          mainColor: giftCertData.mainColor,
                          upperTriangle: giftCertData.secondaryColor,
                          lowerTriangle: giftCertData.tertiaryColor,
                        }}
                        {...giftCertData}
                      />
                    </View>
                  ))
                ) : (
                  <View className={style["none"]}>没有可用的电子礼品卡</View>
                )}
              </>
            )}
          </View>
        </WithMargins>
        <View className={style["bottom-dock-wrapper"]}>
          <C13BottomDock
            onPrimaryClick={{
              cb: () => {
                Taro.navigateBack();
              },
              text: selectedGiftNumber ? "确定" : "返回",
            }}
            onSecondaryClick={null}
          />
        </View>
      </Layout>
    </>
  );
}
